package com.suning.sawp.web.filter;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.suning.framework.webtraffic.UriTraffic;
import com.suning.framework.webtraffic.WebTrafficRejectHandler;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.service.util.GsonUtils;

/**
 * 
 * 功能描述： <br>
 * 店家流控RejectHandler
 *
 * @author 12072522
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class SawpWebTrafficRejectHandler extends WebTrafficRejectHandler {

	private static final Logger LOGGER = LoggerFactory.getLogger(WebTrafficRejectHandler.class);

	/**
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @param matchedUriTraffic
	 *            uriTraffic对象，包含uriPattern（对应配置文件url-pattern、last-segemnt）、
	 *            limit（对应max-concurrency）,参见使用手册
	 * @param uriPatternCurrentCount
	 *            matchedUriTraffic的UriPattern的当前并发量
	 * @throws IOException
	 */
	public void handleOverUriPatternMaxConcurrency(HttpServletRequest request, HttpServletResponse response,
			UriTraffic matchedUriTraffic, int uriPatternCurrentCount) throws IOException {
		LOGGER.warn("request was refused because pending request {} was " + "greater than allowed {}.",
				request.getRequestURI(), matchedUriTraffic.getTraffic());
		ReturnMsg<Void> ret = new ReturnMsg<Void>();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		ret.setRetFlag(ReturnMsg.FAIL);
		ret.setError(ErrorCodeConstants.ERR_0020);
		ret.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0020));
		ServletOutputStream sos = response.getOutputStream();
		sos.write(GsonUtils.toJson(ret, false).getBytes(Charsets.UTF_8));
		sos.flush();
		return;
	}

}
